import java.util.ArrayList;
import java.util.List;

public class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        preorderHelper(root, result);
        return result;
    }

    private void preorderHelper(TreeNode node, List<Integer> result) {
        if (node == null) {
            return;
        }

        // 访问当前节点
        result.add(node.val);

        // 递归访问左子树
        preorderHelper(node.left, result);

        // 递归访问右子树
        preorderHelper(node.right, result);
    }

    // 定义二叉树节点
    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }

    public static void main(String[] args) {
        // 示例 1: 创建二叉树并进行前序遍历
        TreeNode root1 = new TreeNode(1);
        root1.right = new TreeNode(2);
        root1.right.left = new TreeNode(3);

        Solution solution = new Solution();
        List<Integer> result1 = solution.preorderTraversal(root1);
        System.out.println(result1);  // 输出：[1, 2, 3]
    }
}
